// pages/team-management/team-management.js
import user from '../../utils/user.js'
import {
    shake,
    toast,
    confirm,
} from '../../utils/util.js'
import {
    getNewTeamList,
    getSeatListInfo,
    coSeatInfo,
    setSeat,
} from '../../api/app.js'
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isall: false,
        isSelect: false,
        isup: true,
        seatInfo: {},
        teamlist: [],
        teamlistcopy: [],
        timer: null,
        key: '',
        myId: '',
        isAdmin: false,
        isSuperAdmin: false,
        newTeamNum: ''
    },
    doSetSeat(mapList) {
        setSeat({
            isAllchecked: this.data.isall,
            userIds: mapList,
            companyId: user.companyId
        }).then(res => {
            if (res?.data?.code === 500) {
                confirm(`${res?.data?.msg}为发薪项目审批人，需超级管理员取消其审批人身份后，才可取消席位管理员审批`, {
                        confirmText: user.isSuperAdmin ? '进审批流' : '知道了',
                        showCancel: user.isSuperAdmin,
                        confirmColor: '#00D679'
                    })
                    .then(res => {
                        if (user.isSuperAdmin) {
                            wx.navigateTo({
                                url: '/pages/flow/index/index'
                            })
                        }
                    }).catch(err => {
                        console.log(22, err);
                    })
            } else {
                toast('保存成功', 'success')
                this.setData({
                    teamlist: mapList,
                    isSelect: false
                })
                this.coSeatInfo()
                this.getSeatListInfofn()
            }
        })
    },
    // 获取席位列表
    searchSeatInfoList() {
        if (this.data.timer) clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.getNewTeamNum()
        }, 300);
    },
    handleConfirm() {
        // const list = this.data.teamlist.filter(i => i.isselect)
        // let mapList = list.map(i => i.userId)
        // mapList = [...new Set(mapList)]
        if (!this.data.teamlistcopy?.length) {
            confirm('取消发薪席位分配后，用户将无法正常使用相应功能，是否继续？', {
                confirmColor: '#00D679'
            }).then(res => {
                this.doSetSeat(this.data.teamlistcopy)
                this.data.teamlistcopy = []
            }).catch(err => {
                console.log(22, err);
            })
            return
        }
        if (this.data.teamlistcopy.length > this.data.seatInfo.hasSeat) {
            confirm('已达到席位上限，需购买席位后再次分配', {
                confirmText: '去购买',
                confirmColor: '#00D679'
            }).then(res => {
                this.toBuySeat()
            }).catch(err => {
                console.log(22, err);
            })
            return
        }
        this.doSetSeat(this.data.teamlistcopy)
        this.data.teamlistcopy = []
    },
    setCheckData(i, torf) {
        console.log(i, torf, this.data.teamlistcopy, 'siugdug');
        this.data.teamlist[i.index].isselect = torf
        if (torf) {
            this.data.teamlistcopy.push(i.userid)
        } else {
            this.data.teamlistcopy = this.data.teamlistcopy.filter(item => item !== i.userid)
            console.log(this.data.teamlistcopy, 'dughuyhdfguy');
        }
        this.setData({
            teamlist: this.data.teamlist
        })
        let l = 0
        this.data.teamlist.forEach((ele, i) => {
            if (ele.isselect) {
                l += 1
            }
        })
        console.log(l);
        if (l === this.data.teamlist.length) {
            this.setData({
                isall: true
            })
        } else {
            this.setData({
                isall: false
            })
        }
    },
    changeSelect(e) {
        const dataset = e.currentTarget.dataset
        console.log(dataset, 'shjfghudsghuhu');
        if (!dataset.torf) {
            if (dataset.isapprove) { // 在审批流
                if (dataset.isseatadmin) {
                    confirm(`该员工为发薪项目审批人，需超级管理员取消其审批人身份后，才可取消席位管理员审批`, {
                            confirmText: user.isSuperAdmin ? '进审批流' : '知道了',
                            showCancel: user.isSuperAdmin,
                            confirmColor: '#00D679'
                        })
                        .then(res => {
                            if (user.isSuperAdmin) {
                                wx.navigateTo({
                                    url: '/pages/flow/index/index'
                                })
                            } else {
                                this.setCheckData(dataset, true)
                            }
                        }).catch(err => {
                            this.setCheckData(dataset, true)

                        })
                } else {
                    this.setCheckData(dataset, false)
                }
            } else { // 不在审批流
                this.setCheckData(dataset, dataset.torf)
            }
        } else {
            this.setCheckData(dataset, dataset.torf)
        }

    },
    changelistselect(e) {
        console.log(e);
    },
    selectall() {
        console.log(222);
        this.setData({
            isall: !this.data.isall
        })
        if (this.data.isall) {
            this.data.teamlist.forEach((ele => {
                ele.isselect = true
            }))
        } else {
            this.data.teamlist.forEach((ele => {
                ele.isselect = false
            }))
        }
        this.setData({
            teamlist: this.data.teamlist
        })
    },
    toSelect() {
        this.setData({
            isSelect: true
        })
    },
    toSelectcancel() {
        this.setData({
            isSelect: false
        })
    },
    changeipt(e) {
        this.setData({
            teamlist: [],
            key: e.detail.value
        })
        shake(() => {
            this.getSeatListInfofn()
        }, 1000)
    },
    onCallPhone(e) {
        console.log(e);
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone,
        })
    },
    onForbidden() {
        wx.showToast({
            title: '开发中',
            icon: 'none'
        })
    },
    // 去设置页面
    goSetAdmin(event) {
        const {
            userid
        } = event.currentTarget.dataset
        console.log(event.currentTarget.dataset);
        const userInfo = this.data.teamlist.filter(item => {
            if (item.userId == event.currentTarget.dataset.id) {
                return item
            }
        })
        // 是超级管理员 但是不可以进自己的详情页
        // if (user.isSuperAdmin && user.isAdmin && (userid === user.userId)) {
        //     return
        // }
        // 是管理员 只能进普通用户的信息修改页面
        if (user.isSuperAdmin || (user.isAdmin&&event.currentTarget.dataset.admin!==2)) {
            wx.navigateTo({
                url: '/pages/edit-team/edit-team?id=' + event.currentTarget.dataset.id + '&isAdmin=' + userInfo[0].isAdmin + '&isPcAdmin=' + userInfo[0].isPcAdmin + '&name=' + userInfo[0].userName + '&position=' + userInfo[0].position + '&phone=' + userInfo[0].phone + '&isseatadmin=' + event.currentTarget.dataset.isseatadmin + '&isapprove=' + event.currentTarget.dataset.isapprove,
            })
            return
        }
        // 是超级管理员  可以进所有用户的信息修改页面
        if (user.isSuperAdmin && user.isAdmin) {
            console.log(userInfo[0], '这里？？？')
            wx.navigateTo({
                url: '/pages/edit-team/edit-team?id=' + event.currentTarget.dataset.id + '&isAdmin=' + userInfo[0].isAdmin + '&isPcAdmin=' + userInfo[0].isPcAdmin + '&name=' + userInfo[0].userName + '&position=' + userInfo[0].position + '&phone=' + userInfo[0].phone + '&isseatadmin=' + event.currentTarget.dataset.isseatadmin + '&isapprove=' + event.currentTarget.dataset.isapprove,
            })
            return
        }
    },
    toBuySeat() {
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-recharge-bullet/insurance-recharge-bullet'
        })
    },
    close() {
        this.setData({
            isup: false
        })
    },
    // 获取席位信息
    coSeatInfo() {
        coSeatInfo({}).then(res => {
            this.setData({
                seatInfo: res || {}
            })
        })
    },
    // 去新团队成员审核
    goTeamAuditingList() {
        wx.navigateTo({
            url: '/pages/team-auditing-list/team-auditing-list',
        })
    },
    // 跳转到新界面邀请成员
    addTeamList() {
        wx.navigateTo({
            url: '/packagePay/pages/master-invitation-qrcode/master-invitation-qrcode'
        })
    },
    async getNewTeamNum() {
        const result = await getNewTeamList({
            companyId: user.companyId
        })
        this.setData({
            newTeamNum: result.pendingReview
        })
        console.log(result, 'resultresult')
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        user.waitLogin().then(res => {
            this.setData({
                myId: user.userId,
                isAdmin: user.isAdmin,
                isSuperAdmin: user.isSuperAdmin
            })
            if (this.data.isAdmin) {
                this.getNewTeamNum()
            }
            this.getSeatListInfofn()
        })
        this.coSeatInfo()
    },
    async getSeatListInfofn() {
        let res = await getSeatListInfo({
            status: '',
            userName: this.data.key
        })
        console.log(res.list);
        res.list.forEach((ele, i) => {
            if (ele.isSeatAdmin) {
                ele.isselect = true
                this.data.teamlistcopy.push(ele.userId)
            } else {
                ele.isselect = false
            }

        })
        this.setData({
            teamlist: res.list,
            teamlistcopy: this.data.teamlistcopy,
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})